from ...api.encapsulate.carriers import Carriers
from odoo import fields, models, api
from odoo.exceptions import UserError


class RPCourier(models.Model):
    _inherit = "rp.courier"

    # shippypro_name = fields.Char(string='ShipPyPro名称', copy=False, readonly=True, tracking=True)
    # shippypro_id = fields.Char(string='ShipPyPro序号', copy=False, readonly=True, tracking=True)
    third_type = fields.Selection(selection_add=[("shippypro", "shippypro")])
    _sql_constraints = [
        ("unique_name", "UNIQUE(name, third_type)", "承运商名称必须唯一"),
        ("unique_code", "UNIQUE(code, third_type)", "承运商编码必须唯一"),
    ]

    def syn_packages(self):
        carriers = self.search([])
        carriers_map = {}
        for carrier in carriers:
            carriers_map[carrier["third_name"]] = carrier
        name_map = carriers.mapped("third_name")
        package_types = Carriers.get_carrier_package_types()
        for package_type_name in package_types["PackagesTypes"]:
            if package_type_name in carriers_map:
                package_type_list = package_types["PackagesTypes"][package_type_name]
                for package_type in package_type_list:
                    self.env["rp.package.type"]
                    # todo 同步包裹类型
        # print("111")
        # for carrier in carriers:

    def syn_carriers(self):
        """同步承运商信息"""
        carriers_dict = Carriers.get_carriers()  # 调用接口
        # 1、创建/修改承运商
        for courier_name, courier_contents in carriers_dict["Carriers"].items():
            courier = self.courier_deal(courier_name)
            courier.write({"third_type": "shippypro", "third_name": courier_name})
            # 2、清掉承运商服务中的shippypro编码
            # if courier.rp_courier_service_ids:
            #     for s in courier.rp_courier_service_ids:
            #         s.write({'shippypro_id': False})
            # 3、创建/修改承运商服务
            for cts in courier_contents:
                for service_name in cts["ServicesList"]:

                    if cts["Label"]:
                        name = "{}({})".format(service_name, cts["Label"])
                    else:
                        name = service_name
                    # if len(cts['ServicesList']) > 1:

                    service = self.env["rp.courier.mail.route"].search(
                        [("courier_id", "=", courier.id), ("third_server_id", "=", cts["CarrierID"])]
                    )
                    if not service:
                        service = self.env["rp.courier.mail.route"].search(
                            [("courier_id", "=", courier.id), ("name", "=", name)]
                        )

                    if not service:
                        service = self.env["rp.courier.mail.route"].create(
                            {
                                "courier_id": courier.id,
                                "name": name,
                                "third_route_name": service_name,
                                "third_server_id": cts["CarrierID"],
                            }
                        )
                    else:
                        service.write(
                            {
                                "third_route_name": service_name,
                                "third_server_id": cts["CarrierID"],
                            }
                        )

    def courier_deal(self, courier_name):
        """
        判断当前承运商是否存在，不存在则创建
        @param courier_name:承运商名称
        @return: 返回搜索到或者创建出的承运商的rcd(rp.courier)
        """
        courier = self.env["rp.courier"].search(
            [("name", "=ilike", courier_name)], limit=1
        )
        if not courier:
            rcd = self.env["rp.courier"].create(
                {"name": courier_name}
            )
            return rcd
        else:
            return courier

    # def api_test(self):
    #     rcd = self.env['rp.ship.order'].search([('code', '=', 'RP_SO/20230307/00006')])


class RPPackageStandards(models.Model):
    _inherit = "rp.package.standards"
